import Image
from charmodel import model

def comp(a,b):
    count = 0
    for i in range(len(a)):
        if a[i]==b[i]:
            count += 1
    return float(count)/float(len(a))

def check(data, pos):
    flag = False
    for elm in data[pos:pos+8]:
        if 1 in elm:
            flag = True
    return flag

def show(data,s,wide):
    result = []
    for j in range(12):
        for elm in data[s:s+wide]:
            #print elm[j],
            result.append(elm[j])
        #print
    #print
    return result

def readcaptcha(imagefile):
    image_name = imagefile
    im = Image.open(image_name)

    left = 0
    top = 39
    right = 400
    bottom = 51

    im = im.crop((left,top,right,bottom))
    #im.show()
    """
    table = []
    for i in range(256):
        if i != 216:
            table.append(1)
        else:
            table.append(0)
    im = im.point(table, '1')
    im.show()
    """
    s=0
    wide=25
    rawdata =list(im.getdata())
    a= []
    data = []
    imagewide = 400 - left
    for i in range(imagewide):
        for j in range(12):
            a.append( rawdata[i+imagewide*j])
        data.append(a)
        a = []
    for i in range(20):
        numcount = 0
        for elm in data[i]:
            if elm > 150:
                numcount += 1
        if numcount > 5: 
            left = i + 11
            break
    data = data[left:]
    for i in range(len(data)):
        for j in range(len(data[i])):
            if data[i][j] == 216: data[i][j] = 1
            elif data[i][j] in range(200,210): data[i][j] = 2
            else: data[i][j] = 0
   
    imlist = []
    while len(imlist)<3:
        span = 36
        if check(data,s+wide):
            wide = wide +13
            if check(data,s+wide):
                wide = wide + 13
                imlist.append(show(data,s,wide))
                s = s + wide + span
                wide = 25
            else:
                imlist.append(show(data,s,wide))
                s = s + wide + span
                wide = 25
        else:
            imlist.append(show(data,s,wide))
            s = s + wide + span
            wide = 25
        if len(imlist) == 3:
            s = s - span
            pass
    

    for i in range(20,31):
        numcount = 0
        for j in data[s+i]:
            if j ==2: numcount+=1
        if numcount > 4:
            s= s + i+10
            break
    
    while len(imlist)<5:
        span = 36
        if check(data,s+wide):
            wide = wide +13
            if check(data,s+wide):
                wide = wide + 13
                imlist.append(show(data,s,wide))
                s = s + wide + span
                wide = 25
            else:
                imlist.append(show(data,s,wide))
                s = s + wide + span
                wide = 25
        else:
            imlist.append(show(data,s,wide))
            s = s + wide + span
            wide = 25

    
    outcome = []
    for i in range(5):
        percent = [0,0]
        for elm in model:
            if len(imlist[i]) != len(elm['sample']):
                continue
            result = comp(imlist[i],elm['sample'])
            if  result > percent[0]:
                percent[0] = result
                percent[1] = elm
        outcome.append(percent)
    return outcome

if __name__=="__main__":
    pass

def test():
    import glob 
    for i in glob.glob('*.png'):
        imagefile = i
        im = Image.open(i)
        f = readcaptcha(imagefile)
        for j in f:
            print j[1]['name'],j[1]['id'],j[0]
        print ','+','.join([i[1]['id'] for i in f ])
        #im.show() 


